﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;

using CanDoo;
using CanDoo.Core;
using CanDoo.Data;
using CanDoo.Web;
using CanDoo.FineUI;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using FineUIPro;

namespace CanDoo.Oil.WebApp.financeBuyStatement
{
    public partial class Edit : EditPagebase<IBuyStatementContract, BuyStatement>
    {
        public ISupplierContract SupplierContract { get; set; }
        public IPayTypeContract PayTypeContract { get; set; }
        public IUserContract UserContract { get; set; }
        public IBuyAdvanceMoneyContract BuyAdvanceMoneyContract { get; set; }
        public IBuyStatementDetailContract BuyStatementDetailContract { get; set; }
        public IBuyBillContract BuyBillContract { get; set; }
        private bool AppendToEnd = true;
        private int ShowRowCount = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //FineUIListHelper.BindDDL<Supplier>(SupplierContract.GetResolvedTree(), 0L, ed_Supplier,true);
                //FineUIListHelper.BindDDL(SupplierContract.EntityName, this.SupplierContract.GetSelectList(), 0L, ed_Supplier,true);
                //FineUIListHelper.BindDDL<PayType>(PayTypeContract.GetResolvedTree(), 0L, ed_PayType,true);
                FineUIListHelper.BindDDL(PayTypeContract.EntityName, this.PayTypeContract.GetSelectList(), 0L, ed_PayType, true);
                //FineUIListHelper.BindDDL<User>(UserContract.GetResolvedTree(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL(UserContract.EntityName, this.UserContract.GetSelectList(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL<BuyAdvanceMoney>(BuyAdvanceMoneyContract.GetResolvedTree(), 0L, ed_BuyAdvanceMoney);
                //FineUIListHelper.BindDDL(BuyAdvanceMoneyContract.EntityName, this.BuyAdvanceMoneyContract.GetSelectList(), 0L, ed_BuyAdvanceMoney);
                if (PageMode != pagemode.Add)
                {
                    LoadData();
                    ed_Supplier.Readonly = true;
                    ed_NeedPayDate.Readonly = true;
                }
                else
                {
                    ed_PayDate.SetValue(System.DateTime.Now.TimeToStringDate());
                    ed_NeedPayDate.SetValue(System.DateTime.Now.TimeToStringDate());
                    ed_ThisPayedLastMoney.SetValue("0");
                    ed_ThisPayMoney.SetValue("0");
                    ed_AdvanceMoney.SetValue("0");
                }
                    
                #region 表格编辑  Page_Load
                DB.KeepReading(() =>
                {
                    var ChildList = new List<BuyStatementDetail>();
                    if (PageMode != pagemode.Add)
                    {
                        var m = Manager.GetById(EntityId);
                        if(m!=null)
                            ChildList = m.BuyStatementDetails.ToList();
                    }
                    BindChild(ChildList);
                });
                #endregion
            }
        }

        #region 表格编辑
        #region 绑定这个供应商符合条件的应付账单
        private void BindBillList()
        {
            DateTime? needPayDate = ed_NeedPayDate.GetValue().ToDateTime();
            var supplierId = 0L;
            var buyBillList = new List<BuyBill>();
            if (needPayDate == DateTime.MinValue)
                needPayDate = null;

            if (ed_Supplier.Values.Count() > 0 && ed_Supplier.Values[0].ToLong() != 0L)
                supplierId = ed_Supplier.Values[0].ToLong();

            if (supplierId != 0L && needPayDate != null)
                buyBillList = BuyBillContract.Entities.Where(p => p.NeedPayDate <= needPayDate && p.SupplierId == supplierId && p.PayState!=PayStateEnum.AllPayed).ToList();

            var EmptyRowNum = ShowRowCount;
            if (buyBillList != null && buyBillList.Count > EmptyRowNum)
                EmptyRowNum = buyBillList.Count;

            var statementDetailItemList = new List<StatementDetailItem>();
            for (int i = 0; i < ShowRowCount; i++)
            {
                var m = new StatementDetailItem();
                m.Id = "0";
                statementDetailItemList.Add(m);
            }
            GridChild.DataSource = statementDetailItemList;
            GridChild.DataBind();

            int rowid = 0;
            foreach (var m in buyBillList)
            {
                var mEntity = BuyBillContract.EntityChange(m);

                JObject columnValues = new JObject();

                columnValues.Add("BillId", mEntity.BillId);
                columnValues.Add("Code", mEntity.Code);
                columnValues.Add("Name", mEntity.Name);
                columnValues.Add("CreatedDate", mEntity.CreatedDate);
                columnValues.Add("NeedDate", mEntity.NeedDate);
                columnValues.Add("Money", mEntity.Money);
                columnValues.Add("PayedMoney", mEntity.PayedMoney);
                columnValues.Add("WaitMoney", mEntity.WaitMoney);
                columnValues.Add("thisPayMoney", mEntity.thisPayMoney);
                columnValues.Add("thisPayedLastMonoey", mEntity.thisPayedLastMonoey);

                // cancelEdit用来取消编辑
                string updateCellScript = String.Format("F('{0}').cancelEdit();F('{0}').updateCellValue({1},{2});", GridChild.ClientID, rowid, columnValues);

                PageContext.RegisterStartupScript(updateCellScript);
                rowid++;
            }
            
        }
        #endregion


        private void BindChild(List<BuyStatementDetail> childList)
        {
            var GridData = EntityChange(childList);
            GridChild.DataSource = GridData;
            GridChild.DataBind();
        }

        private List<StatementDetailItem> EntityChange(List<BuyStatementDetail> childList)
        {
            var statementDetailItemList = new List<StatementDetailItem>();
            if (childList != null)
            {
                foreach (var m in childList)
                {
                    statementDetailItemList.Add(Manager.EntityChange(m));
                }
            }
            for (int i = statementDetailItemList.Count; i < ShowRowCount; i++)
            {
                var m = new StatementDetailItem();
                m.Id = "0";
                statementDetailItemList.Add(m);
            }
            return statementDetailItemList;
        }

        private OperationResult SaveChild(BuyStatement Entity)
        {
             if (Entity.BuyStatementDetails == null)
                 Entity.BuyStatementDetails = new List<BuyStatementDetail>();
             var mEntities = Entity.BuyStatementDetails;
            // 修改的现有数据
            Dictionary<int, Dictionary<string, object>> modifiedDict = GridChild.GetModifiedDict();
            foreach (int rowIndex in modifiedDict.Keys)
            {
                 var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                 if (rowID >  0L)
                 {
                     var mEntity = mEntities.FirstOrDefault(p => p.Id == rowID);

                     mEntity = UpdateDataRow(modifiedDict[rowIndex], mEntity);
                 }
                 else
                 {
                     BuyStatementDetail mEntity = new BuyStatementDetail();
                     mEntity.Id = IdMaker.NewId();
                     mEntity = UpdateDataRow(modifiedDict[rowIndex], mEntity);
                     mEntities.Add(mEntity);
                 }
            }

            // 删除现有数据
            List<int> deletedRows = GridChild.GetDeletedList();
            foreach (int rowIndex in deletedRows)
            {
                var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                if (rowID >  0L)
                {
                    var item = mEntities.FirstOrDefault(p => p.Id == rowID);
                    if (item != null)
                    {
                        mEntities.Remove(item);
                        BuyStatementDetailContract.Delete(item);
                    }
                }
            }

            // 新增数据
            List<Dictionary<string, object>> newAddedList = GridChild.GetNewAddedList();

            if (AppendToEnd)
            {
                for (int i = 0; i < newAddedList.Count; i++)
                {
                    BuyStatementDetail mEntity = new BuyStatementDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }
            else
            {
                for (int i = newAddedList.Count - 1; i >= 0; i--)
                {
                    BuyStatementDetail mEntity = new BuyStatementDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }

            return new OperationResult(OperationResultType.Success);
        }

        private BuyStatementDetail UpdateDataRow(Dictionary<string, object> rowDict, BuyStatementDetail mEntity)
        {
            if (rowDict.ContainsKey("BillId"))
            {
                if (rowDict["BillId"] != null && rowDict["BillId"].ToLong() >  0L)
                    mEntity.BuyBillId = rowDict["BillId"].ToLong();
                else
                    throw new Exception("应付账单错误");
            }

            if (rowDict.ContainsKey("Name"))
            {
                if (rowDict["Name"] != null)
                    mEntity.Name = rowDict["Name"].ToString();
            }

            if (rowDict.ContainsKey("WaitMoney"))
            {
                if (rowDict["WaitMoney"] != null && !rowDict["WaitMoney"].ToString().IsEmpty())
                    mEntity.BeforeMoney = rowDict["WaitMoney"].ToDouble();
                else
                    throw new Exception("请检查金额是否填写完整");
            }

            if (rowDict.ContainsKey("WaitMoney"))
            {
                if (rowDict["thisPayMoney"] != null && !rowDict["thisPayMoney"].ToString().IsEmpty())
                    mEntity.Money = rowDict["thisPayMoney"].ToDouble();
                else
                    throw new Exception("请检查金额是否填写完整");
            }

            if (rowDict.ContainsKey("thisPayedLastMonoey"))
            {
                if (rowDict["thisPayedLastMonoey"] != null && !rowDict["thisPayedLastMonoey"].ToString().IsEmpty())
                    mEntity.LastedMoney = rowDict["thisPayedLastMonoey"].ToDouble();
                else
                    throw new Exception("请检查金额是否填写完整");
            }

            if (rowDict.ContainsKey("Remark"))
            {
                if (rowDict["Remark"] != null)
                    mEntity.Remark = rowDict["Remark"].ToString();
            }

            return mEntity;
        }
        #endregion
        protected override void LoadData(BuyStatement entity)
        {
            //ed_Name.SetValue(entity.Name);
            ed_Code.SetValue(entity.Code);
            if (entity.Supplier!=null)
            {
                ed_Supplier.Values=new string[] { entity.Supplier.Id.ToString() };
                ed_Supplier.Text=entity.Supplier.Name;
            }
            ed_PayDate.SetValue(entity.PayDate);
            if (!entity.PayTypeId.IsNull())
                ed_PayType.SetValue(entity.PayTypeId);
            if (entity.User!=null)
            {
                ed_User.Values=new string[] { entity.User.Id.ToString() };
                ed_User.Text=entity.User.Name;
            }
            if (entity.BuyAdvanceMoney!=null)
            {
                ed_BuyAdvanceMoney.Values=new string[] { entity.BuyAdvanceMoney.Id.ToString() };
                ed_BuyAdvanceMoney.Text=entity.BuyAdvanceMoney.Name;
                ed_AdvanceMoney.Readonly = false;
            }
            ed_AdvanceMoney.SetValue(entity.AdvanceMoney);
            ed_Remark.SetValue(entity.Remark);
        }

        protected override OperationResult SaveData(BuyStatement entity)
        {
            if (PageMode == pagemode.Add)
            {
                entity.Code = Manager.GetNewCode();
                entity.Name = entity.Code;
            }
            if (ed_Supplier.Values.Count() > 0 && ed_Supplier.Values[0].ToLong() >  0L)
                entity.SupplierId = ed_Supplier.Values[0].ToLong();
            else
                entity.SupplierId = 0L;
            entity.PayDate = ed_PayDate.GetValue().ToNullableDateTime();
            if(entity.PayDate ==DateTime.MinValue)
                entity.PayDate = null;
            if (ed_PayType.GetValue().ToLong() == 0L)
                entity.PayTypeId = 0L;
            else
                entity.PayTypeId = ed_PayType.GetValue().ToLong();
            if (ed_User.Values.Count() > 0 && ed_User.Values[0].ToLong() >  0L)
                entity.UserId = ed_User.Values[0].ToLong();
            else
                entity.UserId = 0L;
            if (ed_BuyAdvanceMoney.Values.Count() > 0 && ed_BuyAdvanceMoney.Values[0].ToLong() >  0L)
                entity.BuyAdvanceMoneyId = ed_BuyAdvanceMoney.Values[0].ToLong();
            else
                entity.BuyAdvanceMoneyId = null;
            entity.AdvanceMoney = ed_AdvanceMoney.GetValue().ToDouble();
            entity.Remark = ed_Remark.GetValue().ToString();
            SaveChild(entity);
            return base.SaveData(entity);
            
        }

        protected void ed_NeedPayDate_TextChanged(object sender, EventArgs e)
        {
            DB.KeepReading(() =>
            {
                BindBillList();
            });
        }

        protected void ed_BuyAdvanceMoney_TextChanged(object sender, EventArgs e)
        {
            var m = ed_BuyAdvanceMoney.Value.ToLong();
            if (m > 0)
            {
                var mEntity = BuyAdvanceMoneyContract.GetById(m);
                if (mEntity != null)
                {
                    ed_AdvanceMoney.SetValue((mEntity.Money - mEntity.UsedMoney));
                    ed_AdvanceMoney.MaxValue = (mEntity.Money - mEntity.UsedMoney);
                    ed_AdvanceMoney.MinValue = 0;
                    ed_AdvanceMoney.Readonly = false;
                }
                else
                {
                    ed_AdvanceMoney.SetValue(0);
                    ed_AdvanceMoney.Readonly = true;
                }
            }
            else
            {
                ed_AdvanceMoney.SetValue(0);
                ed_AdvanceMoney.Readonly = true;
            }
        }
    }
}
